<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>集合封装</title>
</head>
<body>
<script>
  function Set() {
    this.items = {}

    Set.prototype.add = function (value) {
      if (this.has(value)) {
        return false
      }
      this.items[value] = value
    }

    Set.prototype.has = function (value) {
      return this.items.hasOwnProperty(value)
    }

    Set.prototype.remove = function (value) {
      if (!this.has(value)) {
        return false
      }
      delete this.items[value]
      return true
    }

    Set.prototype.clear = function () {
      this.items = {}
    }

    Set.prototype.size = function () {
      return Object.keys(this.items).length
    }

    Set.prototype.values = function () {
      return Object.keys(this.items)
    }

    // 并集
    Set.prototype.union = function (otherSet) {
      let unionSet = new Set();

      let values = this.values();
      for (let i = 0; i < values.length; i++) {
        unionSet.add(values[i])
      }

      values = otherSet.values();
      for (let i = 0; i < values.length; i++) {
        unionSet.add(values[i])
      }

      return unionSet
    }

    // 交集
    Set.prototype.intersection = function (otherSet) {
      let intersectionSet = new Set();

      let values = this.values();
      for (let i = 0; i < values.length; i++) {
        if (otherSet.has(values[i])) {
          intersectionSet.add(values[i])
        }
      }
      return intersectionSet
    }

    // 差集
    Set.prototype.difference = function (otherSet) {
      let differenceSet = new Set();

      let values = this.values()
      for (let i = 0; i < values.length; i++) {
        if (!otherSet.has(values[i])) {
          differenceSet.add(values[i])
        }
      }
      return differenceSet;
    }

    // 子集
    Set.prototype.isSubSet = function (otherSet) {

      let values = otherSet.values();
      for (let i = 0; i < values.length; i++) {
        if (!this.has(values[i])) {
          return false
        }
      }
      return true
    }


  }

  let set1 = new Set();
  set1.add("aaa")
  set1.add("bbb")
  set1.add("ccc")

  let set2 = new Set();
  set2.add("bbb")
  set2.add("ccc")
  set2.add("ddd")

  alert(set1.isSubSet(set2))

</script>

</body>
</html>